package de.bk.timecalc.i18n;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Loads and holds the appropriate resource bundle and returns strings depending
 * on the locale for strings used in time calc core. This class is a singleton.
 * 
 * @author Bastian Krol
 * @version $Revision:$ $Date:$ $Author:$
 */
public class StringFactory
{
  private static final String BUNDLE_NAME = "de.bk.timecalc.time-calc-messages";
  private static final Locale CRYPTIC_MESSAGES_DUMMY_LOCALE = new Locale("zz",
      "ZZ", "cryptic");

  private static StringFactory instance = new StringFactory();

  private ResourceBundle resourceBundle;
  private MessageFormat formatter;
  private Locale locale;

  protected StringFactory()
  {
    super();
    this.formatter = new MessageFormat("");
    this.loadBundleForCurrentLocale();
  }

  public static StringFactory getInstance()
  {
    return instance;
  }

  public void loadBundleForCurrentLocale()
  {
    this.locale = Locale.getDefault();
    this.loadResourceBundle();
  }

  public void loadBundleForLocale(Locale locale)
  {
    this.locale = locale;
    this.loadResourceBundle();
  }

  public void loadCrypticBundle()
  {
    this.locale = CRYPTIC_MESSAGES_DUMMY_LOCALE;
    this.loadResourceBundle();
  }

  private void loadResourceBundle()
  {
    this.resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME, this.locale);
  }

  public final String getString(String stringKey)
  {
    return this.resourceBundle.getString(stringKey);
  }

  public String format(String stringKey, Object... arguments)
  {
    this.formatter.applyPattern(this.getString(stringKey));
    return this.formatter.format(arguments);
  }

  ResourceBundle getResourceBundle()
  {
    return this.resourceBundle;
  }

  /**
   * Returns the locale currently used.
   * 
   * @return the locale currently used
   */
  public String getLocale()
  {
    return this.locale.toString();
  }
}
